using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Threading;
using SkiaSharp;
using SkiaSharp.Skottie;
using SkiaSharp.Views.Desktop;
using SkiaSharp.Views.WPF;

namespace MinoChat.Ui.Controls;

/// <summary>
/// Lottie 动画控件
/// 支持通过 IsPlaying 属性控制动画播放/停止
/// 停止时会优雅地播放到结束帧再静止
/// </summary>
public class LottieControl : SKElement
{
    private Animation? _animation;
    private readonly DispatcherTimer _timer;
    private DateTime _startTime;
    private bool _isStoppingToEnd; // 标记是否正在停止到结束帧

    /// <summary>
    /// Lottie JSON 文件路径（支持相对路径和绝对路径）
    /// </summary>
    public static readonly DependencyProperty SourceProperty =
        DependencyProperty.Register(
            nameof(Source),
            typeof(string),
            typeof(LottieControl),
            new PropertyMetadata(null, OnSourceChanged));

    /// <summary>
    /// 是否正在播放动画
    /// true: 循环播放动画
    /// false: 显示结束帧（静止状态），或等待播放到结束帧再停止
    /// </summary>
    public static readonly DependencyProperty IsPlayingProperty =
        DependencyProperty.Register(
            nameof(IsPlaying),
            typeof(bool),
            typeof(LottieControl),
            new PropertyMetadata(false, OnIsPlayingChanged));

    public string Source
    {
        get => (string)GetValue(SourceProperty);
        set => SetValue(SourceProperty, value);
    }

    public bool IsPlaying
    {
        get => (bool)GetValue(IsPlayingProperty);
        set => SetValue(IsPlayingProperty, value);
    }

    public LottieControl()
    {
        _timer = new DispatcherTimer
        {
            Interval = TimeSpan.FromMilliseconds(1000.0 / 30) // 30 FPS
        };
        _timer.Tick += OnTimerTick;
    }

    private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is LottieControl control)
        {
            control.LoadAnimation(e.NewValue as string);
        }
    }

    private static void OnIsPlayingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is LottieControl control && e.NewValue is bool isPlaying)
        {
            if (isPlaying)
            {
                control.StartAnimation();
            }
            else
            {
                // 如果动画正在播放，则标记为"停止到结束帧"
                if (control._timer.IsEnabled)
                {
                    control.StopAnimation();
                }
                else
                {
                    // 如果动画没有播放，直接显示结束帧
                    if (control._animation != null)
                    {
                        control._animation.SeekFrameTime(control._animation.Duration.TotalSeconds);
                        control.InvalidateVisual();
                    }
                }
            }
        }
    }

    private void LoadAnimation(string? source)
    {
        if (string.IsNullOrEmpty(source))
        {
            _animation?.Dispose();
            _animation = null;
            InvalidateVisual();
            return;
        }

        try
        {
            // 如果是相对路径，转换为基于应用程序目录的绝对路径
            var filePath = source;
            if (!Path.IsPathRooted(source))
            {
                var appDir = AppDomain.CurrentDomain.BaseDirectory;
                filePath = Path.Combine(appDir, source);
            }

            Debug.WriteLine($"[LottieControl] 尝试加载动画: {filePath}");

            if (!File.Exists(filePath))
            {
                Debug.WriteLine($"[LottieControl] 警告: Lottie 文件不存在: {filePath}");
                return;
            }

            var json = File.ReadAllText(filePath);
            _animation = Animation.Parse(json);

            if (_animation != null)
            {
                Debug.WriteLine($"[LottieControl] 动画加载成功，时长: {_animation.Duration.TotalSeconds:F2} 秒");
            }

            if (IsPlaying)
            {
                StartAnimation();
            }
            else
            {
                // 不播放时，显示结束帧
                if (_animation != null)
                {
                    _animation.SeekFrameTime(_animation.Duration.TotalSeconds);
                }
                InvalidateVisual();
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"[LottieControl] 错误: 加载动画失败 - {ex.Message}");
        }
    }

    private void StartAnimation()
    {
        _startTime = DateTime.Now;
        _isStoppingToEnd = false;
        _timer.Start();
    }

    private void StopAnimation()
    {
        // 不立即停止，而是标记为"正在停止到结束帧"
        _isStoppingToEnd = true;
    }

    private void OnTimerTick(object? sender, EventArgs e)
    {
        InvalidateVisual();
    }

    protected override void OnPaintSurface(SKPaintSurfaceEventArgs e)
    {
        base.OnPaintSurface(e);

        var canvas = e.Surface.Canvas;
        canvas.Clear(SKColors.Transparent);

        if (_animation == null)
            return;

        double progress;

        // 只有在 timer 运行时才计算基于时间的进度
        if (_timer.IsEnabled)
        {
            var elapsed = (DateTime.Now - _startTime).TotalSeconds;
            progress = (elapsed % _animation.Duration.TotalSeconds) / _animation.Duration.TotalSeconds;

            // 如果正在停止到结束帧，检查是否到达结束帧
            if (_isStoppingToEnd)
            {
                // 如果当前进度接近结束（> 0.95，即接近结束）
                if (progress > 0.95)
                {
                    // 强制设置为结束帧
                    progress = 1.0;
                    _isStoppingToEnd = false;
                    _timer.Stop();
                }
            }
        }
        else
        {
            // timer 没有运行时，显示结束帧（静止状态）
            progress = 1.0;
        }

        _animation.SeekFrameTime(progress * _animation.Duration.TotalSeconds);

        var bounds = new SKRect(0, 0, e.Info.Width, e.Info.Height);
        _animation.Render(canvas, bounds);
    }
}
